<?php


namespace app\common\model;


use think\Db;
use think\Exception;

class UserLike extends BaseModel{

    protected $updateTime = false;

    public static function addLike($userId,$toUserId){
        Db::startTrans();
        try{
            $count = self::where('user_id',$userId)->where('to_user_id',$toUserId)->whereTime('created_at','today')->lock(true)->count();
            //sleep(1);
            if($count > 0){
                throw new Exception('无法重复点赞','1000');
            }
            self::create([
                'user_id'   => $userId,
                'to_user_id'=> $toUserId
            ]);
            User::where('id',$toUserId)->setInc('like_num',1);
            // 完成任务
            Task::complete(7,$userId);
            Db::commit();
            return ['code'=>1,'msg'=>'点赞成功'];
        }catch(\Exception $e){
            Db::rollback();
            write_log($e->getMessage(),'用户点赞错误');
            if($e->getCode() == 1000){
                return ['code'=>0,'msg'=>$e->getMessage()];
            }
            //write_log($e->getMessage(),'用户点赞错误');
            return ['code'=>0,'msg'=>'点赞失败'];
        }
    }
}